/**
* @Description: WoShop商城
* @Author: 梧桐
* @Copyright: 武汉一一零七科技有限公司©版权所有
* @Link: www.wo-shop.net
* @Contact: QQ:2487937004
*/
<template>
  <view class="index_class">
    <view class="edit-address">
      <form action="" class="new_from" style="display: block;">
		
		<u-form-item :label="$t('收货人')" label-width="150">
			<u-input v-model="addresinfo.contacts" :placeholder="$t('请填写收货人姓名')" />
		</u-form-item>
		
		<u-form-item :label="$t('联系电话')" label-width="150">
			<u-input v-model="addresinfo.phone" :placeholder="$t('请填写联系电话')" />
		</u-form-item>
		
		<u-form-item :label="$t('所在地区')" label-width="150" @click="showRegionPicker">
			<view @click="showRegionPicker">
				<input disabled type="text" v-model="provinceCityArea" placeholder="选择省市区县" />
			</view>
		</u-form-item>
		
		<u-form-item :label="$t('详细地址')" label-width="150">
			<u-input type="textarea" v-model="addresinfo.address" :placeholder="$t('街道,楼牌号等')"/>
		</u-form-item>
		
		<u-form-item :label="$t('设置默认')" label-width="150">
		  <switch :checked="addresinfo.is_default" @change="switch2Change" />
		</u-form-item>
		
      </form>
      <view class="add_btn">
        <button class="cash_btn" @click="NewAddress">{{$t('保存地址')}}</button>
      </view>
    </view>
	<u-picker mode="region" ref="uPicker" :area-code='[provinceInfo.idcode, cityInfo.idcode, areaInfo.idcode]' v-model="showRegion" @confirm="confirm"/>
  </view>
</template>

<script>
import mpvuePicker from '@/components/mpvue-picker/mpvuePicker'
var QQMapWX = require('../mapSdk/qqmap-wx-jssdk.js');
var qqmapsdk;
let addrId = ''
export default {
  components: {
    mpvuePicker
  },
  data() {
    return {
      mode: 'selector',
      addresinfo: {},
      pirkCity: {
        prores: [],
        cityres: [],
        areares: []
      },
      provinceInfo: {
		  idcode:'11',
		  id:'',
		  pro_name:'',
		  code:'',
	  },
      cityInfo: {
		  idcode:'1101',
		  id:'',
		  city_name:'',
		  code:'',
	  },
      areaInfo: {
		  idcode:'110101',
		  id:'',
		  area_name:'',
		  code:'',
	  },
      disabled: 1,
      disabled2: 1,
	  
	  
	  showRegion:false,
	  provinceCityArea:"",
	  rangeJson2: []
    }
  },
  onLoad(option) {
    addrId = option.addrId
    this.getinfo()
    // 实例化API核心类
    qqmapsdk = new QQMapWX({
    	key: 'T65BZ-AN6WI-4CRGL-UGDJF-WOTGE-VWFKP'
    });
    this.rangeJson();
  },
  onShow() {
  },
  computed: {
  },
  watch: {
  },
  methods: {
	  
	confirm(e){
		console.log(e);
		this.provinceInfo.idcode=e.province.value
		this.cityInfo.idcode=e.city.value
		this.areaInfo.idcode=e.area.value
		this.provinceInfo.id=this.padZero(e.province.value,6)
		this.cityInfo.id=this.padZero(e.city.value,6)
		this.areaInfo.id=this.padZero(e.area.value,6)
		this.provinceInfo.pro_name=e.province.label
		this.cityInfo.city_name=e.city.label
		this.areaInfo.area_name=e.area.label
		this.provinceInfo.code=this.padZero(e.province.value,6)
		this.cityInfo.code=this.padZero(e.city.value,6)
		this.areaInfo.code=this.padZero(e.area.value,6)
		this.provinceCityArea = e.province.label +" "+ e.city.label +" "+ e.area.label
	},
	
	//字符串末尾补零
	padZero(num, n) {
		var len = num.toString().length;
		while(len < n) {
			num = num+"0";
			len++;
		}
		return num;
	},	
	
	showRegionPicker(e) {
		this.showRegion = true;
	},
	
    async NewAddress() {
      if (!this.addresinfo.contacts) {
        this.$toast(this.$t('请输入收货人姓名'))
        return false
      }
      if (!this.addresinfo.phone) {
        this.$toast(this.$t('请输入联系人手机号'))
        return false
      }
      if (!this.provinceInfo.id) {
        this.$toast(this.$t('请选择所在省份'));
        return false;
      }
      if (!this.cityInfo.id) {
        this.$toast(this.$t('请选择所在城市'));
        return false;
      }
      if (!this.areaInfo.id) {
        this.$toast(this.$t('请选择所在地区'));
        return false;
      }
      if (!this.addresinfo.address) {
        this.$toast(this.$t('请填写详细地址'))
        return false
      }

	  // 地址返坐标
	  const resLocal = await this.isQuan(this.provinceInfo.pro_name+this.cityInfo.city_name+this.areaInfo.area_name+this.addresinfo.address);
	  // 判断是否在圈内
	  let isRange = 1;//默认可配送
	  if(this.rangeJson2 != null && resLocal != null){
	  		isRange = this.isRange(resLocal, JSON.parse(this.rangeJson2));
	  		isRange = isRange ? 1 : 0;
	  		console.log("计算结果："+isRange);
	  }
      this.$http.getAddressedit({
        contacts: this.addresinfo.contacts,
        dz_id: this.addresinfo.id,
        phone: this.addresinfo.phone,
        address: this.addresinfo.address,
        is_default: this.addresinfo.is_default,
        pro_id: this.provinceInfo.id,
        city_id: this.cityInfo.id,
        area_id: this.areaInfo.id,
		province: this.provinceInfo.pro_name,
		city: this.cityInfo.city_name,
		area: this.areaInfo.area_name,
		datavalue: this.provinceCityArea,
		// 新增坐标和是否在配送范围内
		latitude: resLocal.lat,
		longitude: resLocal.lng,
		is_range: isRange
      }).then(res => {
        if (res.status == 200) {
          this.$toast(res.mess)
          setTimeout(r => {
            this.getback()
          }, 1500)
        }
      })
    },
    getinfo() {
      this.$http.getAddressinfo({
        dz_id: addrId
      }).then(res => {
        if (res.status == 200) {
          this.addresinfo = res.data.address
		  
		  this.provinceInfo.idcode=this.addresinfo.pro_idcode
		  this.cityInfo.idcode=this.addresinfo.city_idcode
		  this.areaInfo.idcode=this.addresinfo.area_idcode
		  this.provinceInfo.id=this.addresinfo.pro_code
		  this.cityInfo.id=this.addresinfo.city_code
		  this.areaInfo.id=this.addresinfo.area_code
		  this.provinceInfo.pro_name=this.addresinfo.pro_name
		  this.cityInfo.city_name=this.addresinfo.city_name
		  this.areaInfo.area_name=this.addresinfo.area_name
		  this.provinceInfo.code=this.addresinfo.pro_code
		  this.cityInfo.code=this.addresinfo.city_code
		  this.areaInfo.code=this.addresinfo.area_code
		  this.provinceCityArea = this.addresinfo.pro_name +" "+ this.addresinfo.city_name +" "+ this.addresinfo.area_name
		  
          if (res.data.address.is_default == 1) {
            this.addresinfo.is_default = true;
          } else {
            this.addresinfo.is_default = false;
          }
		  
        }
      })
    },
    
    switch2Change(e) {
      this.addresinfo.is_default = e.detail.value ? true : false
    },
	
	//查询配送范围
	rangeJson() {
		this.$http.getRangeJson().then(res => {
		    if (res.status == 200) {
		        this.rangeJson2 = res.data;
		    }
		});
	},
	
	// 根据地址查询坐标
	async isQuan(addr) {
	    return new Promise((resolve, reject) => {
	      qqmapsdk.geocoder({
	        address: addr,
	        success: function(res) {
			  // 成功时解析 Promise
	          resolve(res.result.location); 
	        },
	        fail: function(error) {
	          console.error(error);
	        },
	        complete: function(res) {
	        }
	      });
	    });
	  },
	  
	  /** 
	   *  判断一个点是否在多边形内部 
	   *  @param posArray 多边形坐标集合 
	   *  @param point 测试点坐标 
	   *  返回true为真，false为假 
	   *  */  
	
	
	pointInPolygon(point, polygon) {
	    // 计算射线与多边形边界的交点数量
	    const x = point.lat;
	    const y = point.lng;
	    const n = polygon.length;
	    let inside = false;

	    for (let i = 0, j = n - 1; i < n; j = i++) {
	        // 计算当前边的两个顶点坐标
	        const xi = polygon[i][0];
	        const yi = polygon[i][1];
	        const xj = polygon[j][0];
	        const yj = polygon[j][1];
	
	        // 检查射线是否与多边形的一条边相交
	        if ((yi > y) !== (yj > y) && x < (xj - xi) * (y - yi) / (yj - yi) + xi) {
	            inside = !inside;
	        }
	    }
	    return inside;
	},
	
	//判断是否在配送范围内
	isRange(position, data) {
	  let flag = data.some(item => {
	    if (item.name && Array.isArray(item.name)) {
	      return item.name.some(nameItem => {
	        if (Array.isArray(nameItem.paths) && nameItem.paths.length > 0) {
	          const newPaths = nameItem.paths.map(path => new Array(path.lat, path.lng));
			  return this.pointInPolygon(position, newPaths);
	        }
	        return false;
	      });
	    }
	    return false;
	  });
	  return flag;
	}
    
  }
}
</script>

<style lang="less">
page {
  height: 100%;
  background-color: #ffffff;
}
.edit-address{
	padding:0 20upx;
}
.index_class .edit-address{
  background-color: #ffffff;
}
/deep/ .u-form-item--right__content__slot{
	display: block;
}
</style>
